#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <fstream>
#include "Log.hpp"

const std::string unknown = "unknown";
const std::string mydict = "./recource/dict.txt";
const std::string sep = " ";    // 分隔符

class word
{
    // 音标，单词，释义， 同义词（可自己扩展，这里就不写了）
};

class Translater
{
public:
    Translater(std::string dict_path = mydict)
        : _dict_path(dict_path)
    {
        LoadDict();
        Parse();
    }
    
    void LoadDict()
    {
        std::ifstream in(_dict_path);
        std::string line;
        while(std::getline(in, line))
        {
            _lines.push_back(line);
        }
        in.close();
        lg.LogMessage(Debug, "Load dict txt success, path: %s\n", _dict_path.c_str());
    }

    // 按照分隔符切片
    void Parse()
    {
        for(auto &line : _lines)
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos) 
                continue;   // 没找到
            else
            {
                std::string word = line.substr(0, pos);
                std::string chinese = line.substr(pos + sep.size());
                _dict.insert(std::make_pair(word, chinese));
            }
        }
        lg.LogMessage(Debug, "Prase dict txt success\n");
    }

    void debug()
    {
        for( auto &line : _lines )
            std::cout << line << std::endl;

        for(auto &elem : _dict)
            std::cout << elem.first << ":" << elem.second << std::endl;
    }

    std::string Excute(const std::string &word)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end())
            return unknown;
        else
            return _dict[word];
    }

    ~Translater()
    {}

private:
    std::string _dict_path;             // 字典txt所在文件路径
    std::unordered_map<std::string, std::string> _dict; // 解析后的字典
    std::vector<std::string> _lines;    // 字典txt中一行一行的内容
};

